const registerDiv = document.querySelector('.register');   //注册页面的div
const loginDiv = document.querySelector('.login');          //登录页面的div
const registerA = document.querySelector('.register-a');    //注册跳转登录 a标签
const loginA = document.querySelector('.login-a');          //登录跳转注册 a标签
// 注册DOM元素
const registerForm = document.querySelector('.register form');
const loginForm = document.querySelector('.login form');

// 已有账号去登录
registerA.addEventListener('click', function (e) {
    registerDiv.style.display = "none"          //隐藏注册显示登录
    loginDiv.style.display = "block"
})
// 还没有账号去注册
loginA.addEventListener('click', function (e) {
    loginDiv.style.display = "none"              //隐藏登录显示注册
    registerDiv.style.display = "block"
})

// 注册
registerForm.addEventListener('submit', async function (e) {
    e.preventDefault();

    // 获取输入的账号密码
    const username = registerForm.querySelector('[name="username"]').value.trim();
    const password = registerForm.querySelector('[name="password"]').value.trim();

    if (!username || !password) {
        toastr.warning("账号或密码为空", "警告")
        return
    }

    const res = await axios({
        url: '/api/register',
        method: 'post',
        data: {
            username,
            password
        }
    })
    // 判断注册是否成功，若成功则吐司成功并跳转到登录页面并带上用户名
    if (res.data.code === 0) {
        toastr.success(res.data.message, "恭喜")
        setTimeout(() => {
            registerA.click();
            loginDiv.querySelector('input[name=username]').value = username
        }, 1500);
    }
})

// 登录
loginForm.addEventListener('submit', async e => {
    e.preventDefault();

    // 获取账号密码
    const username = loginForm.querySelector('[name=username]').value.trim()
    const password = loginForm.querySelector('[name=password]').value.trim()

    if (!username || !password) {
        toastr.info("请输入账号或者密码", "提示");
    }

    const res = await axios({
        url: '/api/login',
        method: 'post',
        data: {
            username,
            password
        }
    })
    console.log(res);
    if (res.data.code === 0) {
        localStorage.setItem("token",res.data.token);
        toastr.success(res.data.message, "恭喜")
        location.href = "index.html"
    }
})  